package com.ysd.lis.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ysd.common.Result;
import com.ysd.lis.entity.SysParamField;
import com.ysd.lis.mapper.sys.SysParamFieldMapper;
import com.ysd.lis.request.SysFieldOptionsDto;
import com.ysd.lis.request.SysParamDto;
import com.ysd.lis.request.SysParamFieldDto;
import com.ysd.lis.request.SysParamFieldParam;
import com.ysd.lis.service.SysParamFieldService;
import com.ysd.util.ToolsUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * <p>
 * cold_chain.t_user 服务实现类
 * </p>
 *
 * @author peng
 * @since 2022-02-05
 */
@Service
@Slf4j
public class SysParamFieldServiceImpl extends ServiceImpl<SysParamFieldMapper, SysParamField> implements SysParamFieldService {

    @Autowired
    SysParamFieldMapper sysParamFieldMapper;
    @Override
    public Result findSysParamGroupList(SysParamFieldParam param) {
        LambdaQueryWrapper<SysParamField> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysParamField::getDelFlag, 0);
        if (StringUtils.isNotBlank(param.getSeachValue())) {
            lambdaQueryWrapper.and(wrapper -> wrapper.like(SysParamField::getTitle, param.getSeachValue())
                    .or().like(SysParamField::getCode, param.getSeachValue()));
        }
        if (null != param.getGrade()){
            lambdaQueryWrapper.eq(SysParamField::getGrade,param.getGrade());
        }
        if(StringUtils.isNotBlank(param.getPid())){
            lambdaQueryWrapper.eq(SysParamField::getPid,param.getPid());
        }
        lambdaQueryWrapper.orderByAsc(SysParamField::getSeq);
        List<SysParamField> fieldList = sysParamFieldMapper.selectList(lambdaQueryWrapper);
        if(param.getGrade()==0){
            for(SysParamField field : fieldList){
                field.setEditFormItemIndex(0);
            }
        }

        return Result.succ(1, "查询成功", fieldList);
    }

    @Override
    public Result findSysParamFieldList(SysParamFieldParam param)throws JsonProcessingException  {
        LambdaQueryWrapper<SysParamField> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysParamField::getDelFlag, 0);
        if (StringUtils.isNotBlank(param.getSeachValue())) {
            lambdaQueryWrapper.and(wrapper -> wrapper.like(SysParamField::getTitle, param.getSeachValue())
                    .or().like(SysParamField::getCode, param.getSeachValue()));
        }
        if (null != param.getGrade()){
            lambdaQueryWrapper.eq(SysParamField::getGrade,param.getGrade());
        }
        if(StringUtils.isNotBlank(param.getPid())){
            lambdaQueryWrapper.eq(SysParamField::getPid,param.getPid());
        }
        lambdaQueryWrapper.orderByAsc(SysParamField::getSeq);
        List<SysParamField> fieldList = sysParamFieldMapper.selectList(lambdaQueryWrapper);

        List<SysParamFieldDto> fmItems = new ArrayList<>();
        Integer j = 0;
        for(SysParamField item : fieldList){
            SysParamFieldDto fmitm = new SysParamFieldDto();
            BeanUtil.copyProperties(item, fmitm,"fieldOptions");
            fmitm.setVisible(1);
            fmitm.setIsCurrent(j == 0);
            if (ToolsUtils.isNotEmpty(item.getFieldSource()) && item.getFieldSource().equals("3") && ToolsUtils.isNotEmpty(item.getFieldOptions())) {
                ObjectMapper objectMapper = new ObjectMapper();
                SysFieldOptionsDto[] ops = objectMapper.readValue(item.getFieldOptions(), SysFieldOptionsDto[].class);
                fmitm.setFieldOptions(Arrays.asList(ops));
            }
            fmItems.add(fmitm);
            j++;
        }

        return Result.succ(1, "查询成功", fmItems);
    }

    @Override
    public Result addSysParamField(SysParamField field) {
        if(field.getGrade().equals(0)){
            //查询分类code在系统参数下是否存在
            LambdaQueryWrapper<SysParamField> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SysParamField::getCode, field.getCode())
                    .eq(SysParamField::getGrade, 0)
                    .eq(SysParamField::getPid, field.getPid())
                    .eq(SysParamField::getDelFlag, 0);
            Integer cnt = sysParamFieldMapper.selectCount(queryWrapper);
            if (cnt > 0) {
                return Result.fail("有此编码的分组已存在，不能添加");
            }

        }
        int insert = sysParamFieldMapper.insert(field);
        if(insert>0){
            return Result.succ(1,"添加成功",field);
        }else {
            return Result.fail(400,"添加失败","");
        }
    }

    @Override
    public Result editSysParamField(SysParamField field) {

        if(field.getGrade().equals(0)){
            //查询分类code在系统参数下是否存在
            LambdaQueryWrapper<SysParamField> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SysParamField::getCode, field.getCode())
                    .eq(SysParamField::getGrade, 0)
                    .eq(SysParamField::getPid, field.getPid())
                    .eq(SysParamField::getDelFlag, 0)
                    .ne(SysParamField::getId,field.getId());
            Integer cnt = sysParamFieldMapper.selectCount(queryWrapper);
            if (cnt > 0) {
                return Result.fail("有此编码的分组已存在，不能添加");
            }

        }

        int updateById = sysParamFieldMapper.updateById(field);
        if(updateById>0){
            return Result.succ(1,"修改成功",field);
        }else {
            return Result.fail(400,"修改失败","");
        }
    }

    @Override
    public Result deleteSysParamField(SysParamField field) {
        if(field.getGrade()==0){
            LambdaQueryWrapper<SysParamField> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(SysParamField::getDelFlag,0).eq(SysParamField::getPid,field.getId());
            Integer cnt = sysParamFieldMapper.selectCount(queryWrapper);
            if (cnt > 0) {
                return Result.fail("分组下有参数值，不能删除");
            }
        }
        int deleteById = sysParamFieldMapper.deleteById(field.getId());
        if(deleteById>0){
            return Result.succ(1, "删除成功", "");
        }else {
            return Result.fail(400, "删除失败", "");
        }
    }

    @Override
    public Result saveSysParamFieldList(SysParamDto dto) throws JsonProcessingException {
        //先根据pid删除所有得数据
        LambdaQueryWrapper<SysParamField> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(SysParamField::getPid,dto.getId());
        int delete = sysParamFieldMapper.delete(lambdaQueryWrapper);
        List<SysParamFieldDto> paramFieldList = dto.getParamFieldList();

        List<SysParamField> addList = new ArrayList<>();
        for(SysParamFieldDto fieldDto : paramFieldList){
            SysParamField sysParamField = new SysParamField();
            BeanUtil.copyProperties(fieldDto, sysParamField);
            if (ToolsUtils.isNotEmpty(fieldDto.getFieldSource()) && ToolsUtils.isNotEmpty(fieldDto.getFieldOptions())) {
                ObjectMapper objectMapper = new ObjectMapper();
                sysParamField.setFieldOptions(objectMapper.writeValueAsString(fieldDto.getFieldOptions()));
            }
            addList.add(sysParamField);
        }

        boolean b = this.saveOrUpdateBatch(addList);
        if(b){
            return Result.succ(1, "成功", null);
        }else {
            return Result.fail(400,"失败","");
        }

    }


}
